﻿namespace Yom.WebService.Setup
{
    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Text;
    using System.Web;
    using System.Xml;
    using Yom.Common;

    public class SetupEnd
    {
        public void OutWrite()
        {
            HttpResponse Response = HttpContext.Current.Response;
            JsonModel Js = new JsonModel();
            string Msg = string.Empty;
            string dbhost = Factory.Request("dbhost");
            string dbuser = Factory.Request("dbuser");
            string dbpass = Factory.Request("dbpass");
            string dbname = Factory.Request("dbname");
            string loginname = Factory.Request("loginname");
            string username = Factory.Request("username");
            string userpass = Factory.Request("userpass");
            string email = Factory.Request("email");

            string InsertUser = string.Format("INSERT INTO [Yom_Admin] ([LoginName], [LoginPass], [UserName], " + "[Email]) VALUES ('{0}', '{1}', '{2}', '{3}')", loginname, userpass.ToMd5(), username, email);
            string InsertSet = string.Format("INSERT INTO [Yom_Setting] VALUES (1, '申明:本站所有漫画均来源于网络，仅提供漫画在线试看，不提供任何下载！广告联系邮箱: ylqjgm#gmail.com (请将#更换为@)<br />关于漫画的版权归原漫画作者及发行商所有。如有侵犯到您的版权，请联系我们，确认之后立即删除', 'CopyRight (c)2009 <a href=\"http://www.yomhut.com\" target=\"_blank\">YomHut</a>. All Rights. Reserved.', 'YomComic, 带头盔滴衰锅, 邱柯皓, 漫画连载', 'html', 'YomComic, 带头盔滴衰锅, 邱柯皓, 漫画连载', 'ZH-CN', 'Files/Face', 'YomComic', '" + Factory.CurrentUrl.Replace("/Installer/Script/Setup.ashx?Action=End", "") + "', 'Default')");
            string strConn = string.Format("server={0};uid={1};pwd={2};database={3}", dbhost, dbuser, dbpass, dbname);
            SqlConnection conn = new SqlConnection(strConn);
            SqlCommand cmd = new SqlCommand();

            try
            {
                conn.Open();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = InsertUser;
                cmd.ExecuteNonQuery();
                cmd.CommandText = InsertSet;
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                conn.Close();
                conn.Dispose();

                EditConfig(strConn);

                Js.Add("State", 0);
                Js.Add("Title", "安装成功完成!");
                Js.Add("Info", "<p>恭喜您! Yom网络漫画管理系统已经安装完成。</p><p>请记住您的管理员登录帐号为: <span style=\"color:blue\">" + loginname + "</span>, 登录密码为: <span style=\"color:blue\">" + userpass + "</span></p><p>请进入网站FTP查看Installer文件夹是否已被删除, 若为删除则手动删除, 以防止被人恶意重装</p><p style=\"text-align:right\">现在您可以: <a href=\"../Admin.ashx\">登录后台</a> 对网站进行系统详细设置</p>");
                Js.Add("Height", "30px");
                Js.Add("Button", "<input type=\"button\" id=\"close\" value=\"完成\" />");
                Response.Write(new Json(Js));
            }
            catch (Exception ex)
            {
                Js.Add("State", 1);
                Js.Add("Msg", "创建管理员帐号, 设置系统配置失败: " + ex.Message.ToString());
                Response.Write(new Json(Js));
            }
            DelFile();
        }

        private void EditConfig(string strConn)
        {
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.Load(HttpContext.Current.Server.MapPath("~/Installer/Web.Config.bak"));
            XmlNode connectionStrings = doc.SelectSingleNode("configuration/connectionStrings");

            if (File.Exists(HttpContext.Current.Server.MapPath("~/Web.Config")))
            {
                File.Delete(HttpContext.Current.Server.MapPath("~/Web.Config"));
            }

            foreach (XmlNode Set in connectionStrings)
            {
                if (Set.Name == "add")
                {
                    XmlAttribute name = Set.Attributes["name"];
                    XmlAttribute conn = Set.Attributes["connectionString"];

                    if (name.Value == "connectionString")
                        conn.Value = strConn;
                }
            }
            XmlTextWriter Writer = new XmlTextWriter(HttpContext.Current.Server.MapPath("~/Web.Config"), Encoding.UTF8);
            Writer.Formatting = Formatting.Indented;
            doc.Save(Writer);
            Writer.Close();
        }

        private void DelFile()
        {
            try
            {
                Yom.Common.Fso.DeleteFile("~/Installer/images/headerbg.gif");
                Yom.Common.Fso.DeleteFile("~/Installer/images/printerIcon.gif");
                Yom.Common.Fso.DeleteDirectory("~/Installer/images/");
                Yom.Common.Fso.DeleteFile("~/Installer/Script/Clear.sql");
                Yom.Common.Fso.DeleteFile("~/Installer/Script/Setup.ashx");
                Yom.Common.Fso.DeleteFile("~/Installer/Script/Setup.js");
                Yom.Common.Fso.DeleteFile("~/Installer/Script/Setup.sql");
                Yom.Common.Fso.DeleteDirectory("~/Installer/Script/");
                Yom.Common.Fso.DeleteFile("~/Installer/Index.htm");
                Yom.Common.Fso.DeleteFile("~/Installer/License.htm");
                Yom.Common.Fso.DeleteFile("~/Installer/License.txt");
                Yom.Common.Fso.DeleteDirectory("~/Installer/");
            }
            catch { }
        }
    }
}